load("@aspect_rules_js//js:defs.bzl", "js_test")
load("@aspect_rules_js//npm:defs.bzl", "npm_package", "stamped_package_json")
load("@bazel_skylib//rules:copy_file.bzl", "copy_file")

copy_file(
    name = "copy_LICENSE",
    src = "//:LICENSE",
    out = "LICENSE",
)

genrule(
    name = "buildozer_launcher",
    srcs = ["//:launcher.js"],
    outs = ["buildozer.js"],
    cmd = "sed s/_TOOL_/buildozer/ $< > $@",
)

# npm rules live in this subdirectory to avoid a load() statement
# in the parent package leaking to users. This means we need
# to copy the output files so the pkg_npm will find them in the
# output directory for this package.
_PARENT_PACKAGE_FILES = [
    "README.md",
    "buildozer-darwin_amd64",
    "buildozer-darwin_arm64",
    "buildozer-linux_amd64",
    "buildozer-linux_arm64",
    "buildozer-windows_amd64.exe",
]

[
    copy_file(
        name = "copy_%s" % s,
        # go_binary doesn't give a predeclared output for
        # the file in "out" so we have to construct a
        # label to reference the go_binary rule itself.
        src = "//buildozer:%s" % s.replace("_arm64", "-arm64").split("_amd64")[0],
        out = s,
    )
    for s in _PARENT_PACKAGE_FILES
]

stamped_package_json(
    name = "package",
    stamp_var = "BUILD_SCM_VERSION",
)

npm_package(
    name = "buildozer",
    srcs = [
        "LICENSE",
        "buildozer.js",
        "index.js",
        ":package",
    ] + _PARENT_PACKAGE_FILES,
    package = "@bazel/buildozer",
)

js_test(
    name = "integration_test",
    data = [":buildozer"],
    entry_point = "test.js",
)
